#include "app/app.h"

#include "ti_msp_dl_config.h"
#include "hardware/encoder.h"
#include "hardware/lcd.h"
#include "hardware/lcd_init.h"
#include "hardware/uart.h"
#include "hardware/motor.h"
#include "mid/input/input.h"
#include "mid/printf.h"
#include "mid/ui.h"

#include <string.h>

// 说明:
// 1. lcd 驱动为 gc9a01，和 bilibi 教程的不一样
// 2. text.h 和 lcdfont.h 文件需要使用 GB2312 编码(中文字模的编码)

void InitApp();
void MainLoop();
void SwitchMode(eAppMode mode);

static eAppMode gMode = eAM_None;

App* GetApp()
{
    static App gApp;
    static char gInited = 0;

    if (gInited == 0)
    {
        gApp.Init = InitApp;
        gApp.MainLoop  = MainLoop;
        gApp.SwitchMode = SwitchMode;
        gInited = 1;
    }

    return &gApp;
}

void InitApp()
{
    SYSCFG_DL_init();

	InitUART();
	InitEncoder();
	InitInput();

	printf("Init...\n");
	LCD_Init();
	LCD_Fill(0, 0, LCD_W, LCD_H, WHITE);

	NVIC_ClearPendingIRQ(TIMER_0_INST_INT_IRQN);
	NVIC_EnableIRQ(TIMER_0_INST_INT_IRQN);

	GetUIMgr()->Init();
}

void MainLoop()
{
    while(1)
	{
		GetUIMgr()->Update();

		delay_ms(5);
	}
}

void SwitchMode(eAppMode mode)
{
    gMode = mode;
}

eAppMode GetAppMode()
{
    return gMode;
}

// 20ms 中断回调
void TIMER_0_INST_IRQHandler()
{
	switch (DL_TimerA_getPendingInterrupt(TIMER_0_INST))
	{
		case DL_TIMER_IIDX_ZERO: // 0 溢出中断
			ProcessInput();

			if (GetAppMode() == eAM_FIXED_SPEED) // 非定距模式，定时清理电机脉冲数
				ResetEncoder();
			break;
		
		default:
			break;
	}
}